import { Toast } from 'vant'

const state = {
  collectList: JSON.parse(localStorage.getItem('collectList')) || [],
  is_collect: false
}
const getters = {
  collectList(state) {
    localStorage.setItem('collectList', JSON.stringify(state.collectList))
    return state.collectList
  },
  isCollect(state) {
    return state.is_collect
  }
}
const mutations = {
  setIsCollect(state, goods_id) {
    console.log('商品id', goods_id)
    // 查看收藏列表是否有改id
    state.is_collect = state.collectList.some(
      v => v.goods_id === goods_id
    )
  },
  collectGoods(state, goodsInfo) {
    let is_collect = false
    // 获取当前收藏商品id
    const index = state.collectList.findIndex(
      v => v.goods_id === goodsInfo.goods_id
    )
    // 如果index为-1,表示没有对应id
    if (index !== -1) {
      // 有就删除--取消收藏
      state.collectList.splice(index, 1)
      is_collect = false
      Toast.success('取消成功')
    } else {
      // 没有就增加--收藏
      state.collectList.push(goodsInfo)
      is_collect = true
      Toast.success('收藏成功')
    }
    localStorage.setItem('collectList', JSON.stringify(state.collectList))
    state.is_collect = is_collect
    console.log('收藏列表', state.collectList)
  }
}
const actions = {
  collectGoods({ commit }, goodsInfo) {
    commit('collectGoods', goodsInfo)
  },
  setIsCollect({ commit }, goods_id) {
    commit('setIsCollect', goods_id)
  }
}

export default { state, mutations, actions, getters }
